import Vue from 'vue'
import axios from 'axios'
import store from '@/store'
import notification from 'ant-design-vue/es/notification'
import { VueAxios } from './axios'
import { ACCESS_TOKEN } from '@/store/mutation-types'

// 创建 axios 实例
const service = axios.create({
  baseURL: process.env.VUE_APP_API_BASE_URL,
  timeout: 15000
})
const errorKey = 'request-error'

// request interceptor
service.interceptors.request.use(config => {
  const token = Vue.ls.get(ACCESS_TOKEN)
  if (token) {
    config.headers['Authorization'] = 'Bearer ' + token
  }
  return config
}, error => {
  Promise.reject(error)
})

// respone interceptor
service.interceptors.response.use(
  response => { // 响应成功
    // NProgress.done()
    debugger
    const res = response.data
    switch (res.code) {
      case 0:
        return res
      case 1:
        store.dispatch('Logout', { isReqLogOut: false }).then(res => {
          location.reload() // 为了重新实例化vue-router对象 避免bug
        })
    }
    notification.warning({
      key: errorKey,
      message: res.msg || '网络连接超时！',
      duration: 2
    })
    return Promise.reject(res)
  },
  error => { // 响应失败
    console.log('request-error ' + error) // for debug
    notification.warning({
      key: errorKey,
      message: '网络连接超时！',
      duration: 2
    })
    return Promise.reject(error)
  })

const installer = {
  vm: {},
  install (Vue) {
    Vue.use(VueAxios, service)
  }
}

export {
  installer as VueAxios,
  service as axios
}
export default service
